package ciprian.google;

/**
 * @author Ciprian Ursu
 */

import ciprian.google.R;
import ciprian.google.parser.PointsToGPX;
import ciprian.google.utils.Prefs;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.Switch;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.content.Intent;
import android.content.SharedPreferences;

public class SettingsActivity extends Activity implements OnClickListener {
    private RadioGroup appModeRadioGroup;
    private Button singInButton;
    private Button browseRouteButton;
    private EditText recordFileNameEditText;
    private EditText resolutionEditText;
    private CheckBox satelliteCheckBox;
    private CheckBox myLocOverlayCheckBox;
    private CheckBox drawRouteCheckBox;
    private Switch satelliteSwitch;
    private Switch myLocOverlaySwitch;
    private Switch drawRouteSwitch;

    private Toast infoToast;

    private AlphaAnimation loadButtonAppearance = new AlphaAnimation(0, 1);
    private AlphaAnimation loadButtonDisappearance = new AlphaAnimation(1, 0);

    private SharedPreferences settings;
    private SharedPreferences.Editor editor;

    public static final int LOGIN_REQUEST = 0;
    public static final int ROUTE_FILE_REQUEST = 1;

    private int appMode;
    private int timeResolution;
    private String selectedRouteFile = null;

    private boolean satelliteStatus;
    private boolean myLocOverlayStatus;
    private boolean drawRouteStatus;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);

        appModeRadioGroup = (RadioGroup) findViewById(R.id.AppModeRadioGroup);
        browseRouteButton = (Button) findViewById(R.id.LoadRouteButton);
        recordFileNameEditText = (EditText) findViewById(R.id.RecordFileNameEditText);
        resolutionEditText = (EditText) findViewById(R.id.ResolutionEditText);
        singInButton = (Button) findViewById(R.id.SettingSignInButton);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            satelliteCheckBox = (CheckBox) findViewById(R.id.SatelliteStatusCheckBox);
            myLocOverlayCheckBox = (CheckBox) findViewById(R.id.MyLocOverlayStatusCheckBox);
            drawRouteCheckBox = (CheckBox) findViewById(R.id.DrawRouteStatusCheckBox);
        } else {
            satelliteSwitch = (Switch) findViewById(R.id.SatelliteStatusCheckBox);
            myLocOverlaySwitch = (Switch) findViewById(R.id.MyLocOverlayStatusCheckBox);
            drawRouteSwitch = (Switch) findViewById(R.id.DrawRouteStatusCheckBox);
        }

        infoToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);

        loadButtonAppearance.setDuration(500);
        loadButtonDisappearance.setDuration(500);

        settings = Prefs.get();
        editor = settings.edit();
        appMode = settings.getInt(Constants.APPLICATION_MODE, Constants.APPLICATION_MODE_RECORD);
        timeResolution = settings.getInt(Constants.TIME_RESOLUTION, 60);
        satelliteStatus = settings.getBoolean(Constants.SATELLITE_STATUS, false);
        myLocOverlayStatus = settings.getBoolean(Constants.MY_LOC_OVERLAY_STATUS, false);
        drawRouteStatus = settings.getBoolean(Constants.DRAW_ROUTE_STATUS, true);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            satelliteCheckBox.setChecked(satelliteStatus);
            myLocOverlayCheckBox.setChecked(myLocOverlayStatus);
            drawRouteCheckBox.setChecked(drawRouteStatus);
        } else {
            satelliteSwitch.setChecked(satelliteStatus);
            myLocOverlaySwitch.setChecked(myLocOverlayStatus);
            drawRouteSwitch.setChecked(drawRouteStatus);
        }

        if (appMode == Constants.APPLICATION_MODE_RECORD) {
            appModeRadioGroup.check(R.id.RecordModeRadioButton);
            recordFileNameEditText.setVisibility(View.VISIBLE);
            recordFileNameEditText.setText(PointsToGPX.getRouteFileName());
        } else {
            appModeRadioGroup.check(R.id.LoadModeRadioButton);
            selectedRouteFile = settings.getString(Constants.SELECTED_ROUTE_FILE, null);
            if (null != selectedRouteFile) {
                int pos = selectedRouteFile.lastIndexOf('/');
                if (-1 != pos) {
                    String fileName = selectedRouteFile.substring(pos);
                    browseRouteButton.setText(fileName);
                }
            }

            browseRouteButton.setVisibility(View.VISIBLE);
        }

        resolutionEditText.setText(String.valueOf(timeResolution));
    }

    @Override
    public void onResume() {
        super.onResume();

        if (settings.getString(Constants.PARAM_TOKEN, "").length() > 0) {
            // if we have a token in prefs ==> we are connected
            this.setTitle(getText(R.string.logged_in_as) + " "
                    + settings.getString(Constants.PARAM_USERNAME, ""));
            singInButton.setText(R.string.sign_out);
        } else {
            this.setTitle(R.string.not_logged_in);
            singInButton.setText(R.string.sign_in);
        }

        appModeRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup rg, int checkedId) {
                switch (checkedId) {
                case R.id.LoadModeRadioButton:
                    browseRouteButton.startAnimation(loadButtonAppearance);
                    browseRouteButton.setVisibility(View.VISIBLE);

                    recordFileNameEditText.startAnimation(loadButtonDisappearance);
                    recordFileNameEditText.setVisibility(View.INVISIBLE);
                    break;

                case R.id.RecordModeRadioButton:
                    browseRouteButton.startAnimation(loadButtonDisappearance);
                    browseRouteButton.setVisibility(View.INVISIBLE);

                    recordFileNameEditText.startAnimation(loadButtonAppearance);
                    recordFileNameEditText.setVisibility(View.VISIBLE);
                    recordFileNameEditText.setText(PointsToGPX.getRouteFileName());
                    break;
                }
            }
        });

        browseRouteButton.setOnClickListener(this);
        singInButton.setOnClickListener(this);

        appModeRadioGroup.requestFocus();
    }

    @Override
    public void onBackPressed() {
        // back Button was pressed
        int button = appModeRadioGroup.getCheckedRadioButtonId();
        switch (button) {
        case R.id.LoadModeRadioButton:
            if (null != selectedRouteFile) {
                editor.putInt(Constants.APPLICATION_MODE, Constants.APPLICATION_MODE_LOAD);
                editor.putString(Constants.SELECTED_ROUTE_FILE, selectedRouteFile);
            } else {
                infoToast.setText(R.string.warning_route_file_not_selected);
                infoToast.show();
                return;
            }
            break;
        case R.id.RecordModeRadioButton:
            editor.putInt(Constants.APPLICATION_MODE, Constants.APPLICATION_MODE_RECORD);
            String newRouteFile = recordFileNameEditText.getText().toString();

            if (newRouteFile == null || newRouteFile.length() == 0) {
                newRouteFile = PointsToGPX.getTheRouteFilePath();
            } else {
                newRouteFile = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + "/HikingAssistant/" + newRouteFile;

                if (!newRouteFile.endsWith(".gpx"))
                    newRouteFile += ".gpx";
            }

            editor.putString(Constants.SELECTED_ROUTE_FILE, newRouteFile);
            break;
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            editor.putBoolean(Constants.SATELLITE_STATUS, satelliteCheckBox.isChecked());
            editor.putBoolean(Constants.MY_LOC_OVERLAY_STATUS, myLocOverlayCheckBox.isChecked());
            editor.putBoolean(Constants.DRAW_ROUTE_STATUS, drawRouteCheckBox.isChecked());
        } else {
            editor.putBoolean(Constants.SATELLITE_STATUS, satelliteSwitch.isChecked());
            editor.putBoolean(Constants.MY_LOC_OVERLAY_STATUS, myLocOverlaySwitch.isChecked());
            editor.putBoolean(Constants.DRAW_ROUTE_STATUS, drawRouteSwitch.isChecked());
        }

        editor.putInt(Constants.TIME_RESOLUTION,
                Integer.parseInt(resolutionEditText.getText().toString()));

        editor.commit();
        goBackState();

        super.onBackPressed();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == LOGIN_REQUEST) {
            if (resultCode == RESULT_OK) {
                // update the title
                this.setTitle(getText(R.string.logged_in_as) + " "
                        + settings.getString(Constants.PARAM_USERNAME, ""));
            } else {
                // update the title:
                this.setTitle(R.string.not_logged_in);
            }
        } else if (requestCode == ROUTE_FILE_REQUEST) {
            if (resultCode == RESULT_OK) {
                selectedRouteFile = data.getStringExtra(Constants.SELECTED_ROUTE_FILE);
                if (null != selectedRouteFile) {
                    int pos = selectedRouteFile.lastIndexOf('/');
                    if (-1 != pos) {
                        String fileName = selectedRouteFile.substring(pos);
                        browseRouteButton.setText(fileName);
                    }
                }
            } else {

            }
        }
    }

    /**
     * Handle the click event.
     */
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.LoadRouteButton:
            openFileBrowser();
            break;

        case R.id.SettingSignInButton:
            if (settings.getString(Constants.PARAM_TOKEN, "").length() > 0) {
                // user hit on sign out
                editor.putString(Constants.PARAM_TOKEN, "");
                editor.putString(Constants.PARAM_PASSWORD, "");

                editor.commit();
                this.setTitle(R.string.not_logged_in);
                singInButton.setText(R.string.sign_in);
            } else {
                // not logged in ==> login
                enterLoginActivity();
            }
            break;
        }
    }

    /**
     * Opens the File Browser activity.
     */
    protected void openFileBrowser() {
        Intent intent = new Intent(this, FileBrowserActivity.class);
        this.startActivityForResult(intent, ROUTE_FILE_REQUEST);
    }

    /**
     * Opens the Login activity.
     */
    protected void enterLoginActivity() {
        Intent intent = new Intent(this, AuthenticatorActivity.class);
        this.startActivityForResult(intent, LOGIN_REQUEST);
    }

    /**
     * Exits the current state.
     */
    protected void goBackState() {
        this.finish();
    }
}
